<template>
  <div class="room-page">
    <!-- 顶部导航 -->
    <nav class="navbar">
      <div class="container">
        <div class="nav-content">
          <div class="room-info-nav">
            <h1>🏠 {{ roomInfo.name }}</h1>
            <div class="room-id-wrapper">
              <span class="room-id">房间ID: {{ $route.params.id }}</span>
              <button @click="copyRoomId" class="copy-btn" title="复制房间ID">
                <span v-if="copySuccess">✅</span>
                <span v-else>📋</span>
              </button>
            </div>
          </div>
          <div class="nav-actions">
            <button @click="leaveRoom" class="btn btn-secondary">
              🚪 离开房间
            </button>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <div class="container">
        <div class="room-layout">
          <!-- 左侧：玩家列表和房间设置 -->
          <aside class="sidebar">
            <!-- 玩家列表 -->
            <section class="players-section card">
              <div class="players-header">
                <h3>👥 玩家列表 ({{ roomInfo.players.length }}/{{ roomInfo.maxPlayers }})</h3>
              </div>
              <div class="players-list">
                <div v-for="player in roomInfo.players" :key="player.id" class="player-item" :class="{
                  'is-owner': player.isOwner,
                  'is-ready': player.isReady,
                  'is-current-user': player.id === currentUserId
                }">
                  <div class="player-avatar">
                    <img :src="getAvatarUrl(player.avatarUrl || player.avatar)" class="avatar-img" alt="头像" />
                  </div>
                  <div class="player-info">
                    <div class="player-name">
                      {{ player.name }}
                      <span v-if="player.isOwner" class="owner-badge">👑</span>
                    </div>
                    <div class="player-status">
                      <span v-if="player.isReady" class="status-ready">✅ 已准备</span>
                      <span v-else class="status-waiting">⏳ 等待中</span>
                    </div>
                  </div>
                  <div class="player-actions">
                    <button v-if="player.id === currentUserId" @click="toggleReady" 
                            class="btn btn-sm" :class="player.isReady ? 'btn-secondary' : 'btn-primary'" 
                            :disabled="isUpdatingReady">
                      {{ isUpdatingReady ? '更新中...' : (player.isReady ? '取消准备' : '准备') }}
                    </button>
                    <button v-if="isRoomOwner && player.id !== currentUserId" @click="kickPlayer(player)"
                            class="btn btn-sm btn-danger">
                      🚪 踢出
                    </button>
                  </div>
                </div>

                <!-- 空位显示 -->
                <div v-for="n in Math.max(0, roomInfo.maxPlayers - roomInfo.players.length)" :key="`empty-${n}`"
                     class="player-item empty-slot">
                  <div class="player-avatar empty">➕</div>
                  <div class="player-info">
                    <div class="player-name">等待玩家加入...</div>
                  </div>
                </div>
              </div>
            </section>

            <!-- 开始游戏按钮 -->
            <section class="game-controls card">
              <button v-if="isRoomOwner" @click="startGame" class="btn btn-success btn-large" 
                      :disabled="!canStartGame || isStartingGame">
                <span v-if="isStartingGame">🕐 开始中...</span>
                <span v-else-if="canStartGame">🎯 开始画线圈地</span>
                <span v-else>等待玩家准备</span>
              </button>
              <div v-else class="waiting-message">
                <span v-if="currentPlayer?.isReady">✅ 已准备，等待房主开始游戏</span>
                <span v-else>请点击"准备"按钮</span>
              </div>
            </section>
          </aside>

          <!-- 右侧：聊天区域 -->
          <section class="chat-section">
            <div class="chat-container card">
              <div class="chat-header">
                <h3>💬 房间聊天</h3>
                <button @click="clearChat" class="btn btn-sm btn-secondary">清空</button>
              </div>

              <div ref="chatMessagesRef" class="chat-messages" v-if="!isLoadingChat">
                <div v-for="message in chatMessages" :key="message.id" class="message" :class="{
                  'is-own-message': message.userId === currentUserId,
                  'is-system-message': message.type === 'system'
                }">
                  <div v-if="message.type === 'system'" class="system-message">
                    <span class="system-icon">🤖</span>
                    {{ message.content }}
                  </div>
                  <div v-else class="user-message">
                    <div class="message-avatar">
                      <img :src="getAvatarUrl(message.userAvatarUrl || message.userAvatar || '1')" class="avatar-img" alt="头像" />
                    </div>
                    <div class="message-content">
                      <div class="message-header">
                        <span class="message-author">{{ message.userName }}</span>
                        <span class="message-time">{{ formatTime(message.timestamp) }}</span>
                      </div>
                      <div class="message-text selectable-text">{{ message.content }}</div>
                    </div>
                  </div>
                </div>
              </div>
              
              <div v-else class="loading-chat">
                <div class="loading-spinner"></div>
                <p>正在加载聊天记录...</p>
              </div>

              <div class="chat-input">
                <div class="input-group">
                  <input v-model="newMessage" type="text" placeholder="输入消息..." class="form-input"
                         @keyup.enter="sendMessage" maxlength="200" :disabled="isSendingMessage" />
                  <button @click="sendMessage" class="btn btn-primary" :disabled="!newMessage.trim() || isSendingMessage">
                    {{ isSendingMessage ? '发送中...' : '发送' }}
                  </button>
                </div>
                <div class="quick-messages">
                  <button v-for="quick in quickMessages" :key="quick" @click="sendQuickMessage(quick)"
                          class="quick-btn" :disabled="isSendingMessage">
                    {{ quick }}
                  </button>
                </div>
              </div>
            </div>
          </section>
        </div>
      </div>
    </main>

    <!-- 离开房间确认弹窗 -->
    <div v-if="showLeaveConfirmModal" class="modal-overlay" @click="cancelLeaveRoom">
      <div class="leave-modal" @click.stop>
        <div class="leave-modal-header">
          <div class="leave-icon-small">🚪</div>
          <h3>离开房间</h3>
          <button @click="cancelLeaveRoom" class="leave-close">×</button>
        </div>
        <div class="leave-modal-body">
          <div class="leave-warning">⚠️</div>
          <p class="leave-message-compact">确定要离开房间吗？</p>
          <p class="leave-note-compact">离开后需要重新加入房间</p>
        </div>
        <div class="leave-modal-footer">
          <button @click="cancelLeaveRoom" class="btn-compact btn-compact-secondary">取消</button>
          <button @click="confirmLeaveRoom" class="btn-compact btn-compact-danger" :disabled="isLeavingRoom">
            {{ isLeavingRoom ? '离开中...' : '离开' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 通知组件 -->
    <div v-if="notification.show" class="notification-overlay">
      <div class="notification" :class="`notification-${notification.type}`">
        <div class="notification-icon">
          <span v-if="notification.type === 'success'">✅</span>
          <span v-if="notification.type === 'warning'">⚠️</span>
          <span v-if="notification.type === 'error'">❌</span>
          <span v-if="notification.type === 'info'">ℹ️</span>
        </div>
        <div class="notification-message">{{ notification.message }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { roomAPI } from '@/api/room'
import * as signalR from '@microsoft/signalr'

// 静态导入所有头像
import avatar1 from '/images/avatar1.png'
import avatar2 from '/images/avatar2.png'
import avatar3 from '/images/avatar3.png'
import avatar4 from '/images/avatar4.png'
import avatar5 from '/images/avatar5.png'
import avatar6 from '/images/avatar6.png'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 头像映射
const avatarMap = {
  '1': avatar1,
  '2': avatar2,
  '3': avatar3,
  '4': avatar4,
  '5': avatar5,
  '6': avatar6
}

// 获取头像URL的方法
const getAvatarUrl = (avatarUrl) => {
  const avatarNumber = avatarUrl || '1'
  return avatarMap[avatarNumber] || avatar1
}

// DOM 引用
const chatMessagesRef = ref(null)

// 当前用户ID
const currentUserId = computed(() => userStore.userInfo?.id || '')

// 状态管理
const isStartingGame = ref(false)
const isStartingLineDrawingGame = ref(false)
const copySuccess = ref(false)
const isLoadingChat = ref(true)
const isUpdatingReady = ref(false)
const isSendingMessage = ref(false)
const isLeavingRoom = ref(false)
const showLeaveConfirmModal = ref(false)

// 房间信息
const roomInfo = reactive({
  id: '',
  name: '',
  maxPlayers: 0,
  players: [],
  ownerId: '',
  status: 'waiting'
})

// 聊天相关
const newMessage = ref('')
const chatMessages = ref([])
const quickMessages = ref([
  '准备好了！', '等等我', '开始吧', '好的', '厉害！', '再来一局'
])

// 通知系统
const notification = ref({
  show: false,
  message: '',
  type: 'info'
})

// 计算属性
const isRoomOwner = computed(() => {
  return roomInfo.ownerId === currentUserId.value
})

const currentPlayer = computed(() => {
  return roomInfo.players.find(p => p.id === currentUserId.value)
})

const canStartGame = computed(() => {
  if (!roomInfo.players || roomInfo.players.length < 2) return false
  return roomInfo.players.every(p => p.isReady)
})

// 复制房间ID功能
const copyRoomId = async () => {
  try {
    const roomId = route.params.id
    await navigator.clipboard.writeText(roomId)
    copySuccess.value = true
    showNotification('房间ID已复制到剪贴板', 'success')
    
    setTimeout(() => {
      copySuccess.value = false
    }, 2000)
  } catch (error) {
    const textArea = document.createElement('textarea')
    textArea.value = route.params.id
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    
    copySuccess.value = true
    showNotification('房间ID已复制到剪贴板', 'success')
    setTimeout(() => {
      copySuccess.value = false
    }, 2000)
  }
}

// 切换准备状态
const toggleReady = async () => {
  const player = roomInfo.players.find(p => p.id === currentUserId.value)
  if (!player || isUpdatingReady.value) return

  isUpdatingReady.value = true
  try {
    const newReadyState = !player.isReady
    const response = await roomAPI.toggleReady(roomInfo.id, newReadyState)
    
    if (response.success || response.code === 1000) {
      player.isReady = newReadyState
      addSystemMessage(`${player.name} ${newReadyState ? '已准备' : '取消准备'}`)
    } else {
      showNotification(response.message || '操作失败', 'error')
    }
  } catch (error) {
    console.error('切换准备状态失败:', error)
    showNotification('操作失败，请重试', 'error')
  } finally {
    isUpdatingReady.value = false
  }
}

// 房主开始游戏 - 现在启动画线圈地游戏
const startGame = async () => {
  if (!canStartGame.value || isStartingGame.value) return

  isStartingGame.value = true
  try {
    // 调用原有的房间开始游戏API
    const response = await roomAPI.startGame(roomInfo.id)
    
    if (response.success || response.code === 1000) {
      addSystemMessage('画线圈地游戏开始！正在连接...')
      
      // 检查响应中是否包含gameId
      const gameId = response.data?.gameId || response.gameId
      if (gameId) {
        // 直接跳转到画线圈地游戏页面
        setTimeout(() => {
          router.push({
            name: 'LineDrawingGame',
            params: { gameId: gameId },
            query: { 
              playerId: userStore.userInfo?.id,
              playerName: userStore.userInfo?.username 
            }
          })
        }, 1000)
      } else {
        console.error('响应中缺少gameId:', response)
        showNotification('游戏ID获取失败', 'error')
      }
    } else {
      showNotification(response.message || '开始游戏失败', 'error')
    }
  } catch (error) {
    console.error('开始游戏失败:', error)
    showNotification('开始游戏失败，请重试', 'error')
  } finally {
    isStartingGame.value = false
  }
}

// 踢出玩家
const kickPlayer = async (player) => {
  if (!confirm(`确定要踢出玩家 "${player.name}" 吗？`)) return

  try {
    const response = await roomAPI.kickPlayer(roomInfo.id, player.id)
    
    if (response.success || response.code === 1000) {
      const index = roomInfo.players.findIndex(p => p.id === player.id)
      if (index > -1) {
        roomInfo.players.splice(index, 1)
        addSystemMessage(`玩家 "${player.name}" 已被踢出房间`)
      }
    } else {
      showNotification(response.message || '踢出玩家失败', 'error')
    }
  } catch (error) {
    console.error('踢出玩家失败:', error)
    showNotification('操作失败，请重试', 'error')
  }
}

// 离开房间
const leaveRoom = () => {
  showLeaveConfirmModal.value = true
}

const confirmLeaveRoom = async () => {
  if (isLeavingRoom.value) return
  
  isLeavingRoom.value = true
  try {
    await roomAPI.leaveRoom(roomInfo.id)
    showNotification('已离开房间', 'success')
    router.push('/lobby')
  } catch (error) {
    console.error('离开房间失败:', error)
    showNotification('离开房间失败', 'error')
    isLeavingRoom.value = false
    showLeaveConfirmModal.value = false
  }
}

const cancelLeaveRoom = () => {
  showLeaveConfirmModal.value = false
}

// 聊天相关
const sendMessage = async () => {
  if (!newMessage.value.trim() || isSendingMessage.value) return

  const messageContent = newMessage.value.trim()
  newMessage.value = ''
  isSendingMessage.value = true

  try {
    const response = await roomAPI.sendMessage(roomInfo.id, messageContent)
    
    if (response.success || response.code === 1000) {
      const message = {
        id: Date.now(),
        type: 'user',
        userId: currentUserId.value,
        userName: currentPlayer.value?.name || userStore.userInfo?.username || '玩家',
        userAvatarUrl: currentPlayer.value?.avatarUrl || userStore.userInfo?.avatarUrl || '1',
        content: messageContent,
        timestamp: Date.now()
      }
      chatMessages.value.push(message)
      scrollToBottom()
    } else {
      showNotification(response.message || '发送消息失败', 'error')
      newMessage.value = messageContent // 恢复消息内容
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    showNotification('发送消息失败，请重试', 'error')
    newMessage.value = messageContent
  } finally {
    isSendingMessage.value = false
  }
}

const sendQuickMessage = (message) => {
  newMessage.value = message
  sendMessage()
}

const addSystemMessage = (content) => {
  const message = {
    id: Date.now(),
    type: 'system',
    content,
    timestamp: Date.now()
  }
  chatMessages.value.push(message)
  scrollToBottom()
}

const clearChat = () => {
  if (confirm('确定要清空聊天记录吗？')) {
    chatMessages.value = []
  }
}

const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const scrollToBottom = () => {
  nextTick(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
    }
  })
}

// 显示通知
const showNotification = (message, type = 'info') => {
  notification.value = {
    show: true,
    message,
    type
  }
  setTimeout(() => {
    notification.value.show = false
  }, 3000)
}

// 加载房间数据和聊天历史
const loadRoomData = async () => {
  const roomId = route.params.id
  
  // 首先设置房间ID，确保后续API调用有正确的ID
  roomInfo.id = roomId
  
  try {
    // 获取房间信息
    const roomResponse = await roomAPI.getRoomInfo(roomId)
    const roomData = roomResponse.data
    
    // 调试：输出完整的响应数据
    console.log('房间API响应:', roomResponse)
    console.log('房间数据:', roomData)

    // 更新房间信息，保持ID不变
    roomInfo.name = roomData.roomName || roomData.name || '未知房间'
    roomInfo.maxPlayers = roomData.MaxPlayers || roomData.maxPlayers || 4
    roomInfo.ownerId = roomData.HostId || roomData.hostId || roomData.ownerId || ''
    
    // 更新玩家列表
    roomInfo.players = (roomData.Players || roomData.players || []).map(p => ({
      id: p.PlayerId || p.playerId || p.id || '',
      name: p.PlayerName || p.playerName || p.name || '未知玩家',
      isOwner: p.IsHost || p.isHost || p.isOwner || (p.PlayerId === roomInfo.ownerId),
      isReady: p.IsReady || p.isReady || false,
      avatarUrl: p.Avatar || p.avatar || p.avatarUrl || '1'
    }))

  } catch (error) {
    console.error('获取房间信息失败:', error)
    showNotification('房间不存在或已被删除', 'error')
    router.push('/lobby')
    return
  }
}

// 加载聊天历史
const loadChatHistory = async () => {
  try {
    // 等待1秒后加载聊天记录
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const chatResponse = await roomAPI.getChatHistory(roomInfo.id)
    if (chatResponse.success || chatResponse.code === 1000) {
      chatMessages.value = (chatResponse.data?.messages || []).map(msg => ({
        id: msg.id || Date.now(),
        type: msg.type || 'user',
        userId: msg.userId || msg.senderId,
        userName: msg.userName || msg.senderName || '玩家',
        userAvatarUrl: msg.userAvatarUrl || msg.senderAvatar || '1',
        content: msg.content || msg.message || '',
        timestamp: msg.timestamp || msg.createdAt || Date.now()
      }))
    }
    
    // 添加欢迎消息
    if (chatMessages.value.length === 0) {
      addSystemMessage('欢迎来到房间！请准备开始游戏。')
    }
    
  } catch (error) {
    console.error('加载聊天历史失败:', error)
    // 即使聊天历史加载失败，也显示欢迎消息
    addSystemMessage('欢迎来到房间！请准备开始游戏。')
  } finally {
    isLoadingChat.value = false
    scrollToBottom()
  }
}

const roomSignal = {
  conn: null,
  joinedRoomId: null,
}

async function ensureRoomSignalR() {
  console.log('[调试] ensureRoomSignalR 开始')
  if (roomSignal.conn && roomSignal.conn.state === signalR.HubConnectionState.Connected) {
    console.log('[调试] SignalR连接已存在且已连接，复用现有连接')
    return roomSignal.conn
  }
  const token = localStorage.getItem('token') || sessionStorage.getItem('token') || ''
  const baseUrl = (import.meta.env.VITE_API_BASE_URL || 'http://localhost:5128/api').replace(/\/api$/, '')
  console.log('[调试] 创建新的SignalR连接', { baseUrl, hasToken: !!token })
  
  const conn = new signalR.HubConnectionBuilder()
    .withUrl(`${baseUrl}/gameHub`, { accessTokenFactory: () => token })
    .withAutomaticReconnect()
    .build()
    
  // 防重复绑定
  conn.off('GameStarted')
  conn.off('RoomStatusChanged')
  conn.off('RoomChatJoined')
  conn.off('Error')
  
  conn.on('RoomChatJoined', data => {
    console.log('[调试] [前端] 收到 RoomChatJoined 事件:', data)
  })
  conn.on('Error', msg => {
    console.warn('[调试] [前端] 收到 Hub Error:', msg)
  })
  conn.on('GameStarted', payload => {
    console.log('[调试] [前端] 收到 GameStarted 事件:', payload)
    try {
      // 兼容大小写字段名
      const gameId = payload?.GameId || payload?.gameId
      if (!payload || !gameId) {
        console.warn('[调试] [前端] GameStarted事件数据无效:', payload)
        return
      }
      if (router.currentRoute.value.name !== 'LineDrawingGame') {
        console.log('[调试] [前端] 执行游戏跳转 - GameId:', gameId)
        addSystemMessage('游戏已开始，正在跳转...')
        router.push({ 
          name: 'LineDrawingGame', 
          params: { gameId: gameId },
          query: { 
            playerId: userStore.userInfo?.id,
            playerName: userStore.userInfo?.username 
          }
        })
      } else {
        console.log('[调试] [前端] 已在游戏页面，跳过跳转')
      }
    } catch (e) {
      console.error('[调试] [前端] 处理 GameStarted 事件失败:', e)
    }
  })
  conn.on('RoomStatusChanged', data => {
    console.log('[调试] [前端] 收到 RoomStatusChanged 事件:', data)
    try {
      if (!data) {
        console.warn('[调试] [前端] RoomStatusChanged事件数据为空')
        return
      }
      // 兜底：只要房间状态为 Playing 且有 GameId，就跳转
      const gameId = data.GameId || data.gameId
      const status = (data.Status || data.status || '').toString().toLowerCase()
      
      console.log('[调试] [前端] 解析RoomStatusChanged数据 - Status:', status, 'GameId:', gameId)
      
      if ((status === 'playing' || status === 'play') && gameId) {
        if (router.currentRoute.value.name !== 'LineDrawingGame') {
          console.log('[调试] [前端] 通过RoomStatusChanged执行跳转 - GameId:', gameId)
          addSystemMessage('房间进入游戏中，正在跳转...')
          router.push({ 
            name: 'LineDrawingGame', 
            params: { gameId: gameId },
            query: { 
              playerId: userStore.userInfo?.id,
              playerName: userStore.userInfo?.username 
            }
          })
        } else {
          console.log('[调试] [前端] 已在游戏页面，跳过RoomStatusChanged跳转')
        }
      } else {
        console.log('[调试] [前端] RoomStatusChanged不满足跳转条件 - Status:', status, 'GameId:', gameId)
      }
    } catch (e) {
      console.error('[调试] [前端] 处理 RoomStatusChanged 事件失败:', e)
    }
  })
  
  console.log('[调试] 开始建立SignalR连接')
  await conn.start()
  console.log('[调试] SignalR连接建立成功')
  roomSignal.conn = conn
  return conn
}

async function joinRoomSignalGroup(roomId) {
  console.log('[调试] joinRoomSignalGroup 开始 - RoomId:', roomId)
  const conn = await ensureRoomSignalR()
  if (roomSignal.joinedRoomId === roomId) {
    console.log('[调试] 已加入此房间的SignalR组，跳过重复加入')
    return
  }
  console.log('[调试] 调用 JoinRoomChat - RoomId:', roomId)
  await conn.invoke('JoinRoomChat', roomId)
  console.log('[调试] JoinRoomChat 调用完成')
  roomSignal.joinedRoomId = roomId
}

onMounted(async () => {
  console.log('[调试] RoomPage onMounted 开始')
  await loadRoomData()
  
  // 若当前用户未在房间内，自动加入一次，避免收不到广播
  try {
    if (!currentUserId.value) {
      console.log('[调试] 当前用户ID为空，尝试初始化用户状态')
      // 尝试从用户仓库初始化（如果需要）
      try { await userStore.init?.() } catch {}
    }
    console.log('[调试] 当前用户ID:', currentUserId.value)
    console.log('[调试] 房间玩家列表:', roomInfo.players)
    
    const isMember = !!roomInfo.players.find(p => p.id === currentUserId.value)
    console.log('[调试] 用户是否为房间成员:', isMember)
    
    if (!isMember) {
      console.log('[调试] 用户不在房间中，尝试自动加入房间')
      const joinResp = await roomAPI.joinRoom(roomInfo.id)
      console.log('[调试] 自动加入房间结果:', joinResp)
      
      if (joinResp.success || joinResp.code === 1000) {
        addSystemMessage('你已加入房间')
        console.log('[调试] 自动加入成功，重新拉取房间信息')
        // 重新拉取房间信息，刷新玩家列表
        const refreshed = await roomAPI.getRoomInfo(roomInfo.id)
        console.log('[调试] 刷新后的房间信息:', refreshed)
        const roomData = refreshed.data || {}
        roomInfo.players = (roomData.Players || roomData.players || []).map(p => ({
          id: p.PlayerId || p.playerId || p.id || '',
          name: p.PlayerName || p.playerName || p.name || '未知玩家',
          isOwner: p.IsHost || p.isHost || p.isOwner || (p.PlayerId === (roomData.HostId || roomData.hostId || roomInfo.ownerId)),
          isReady: p.IsReady || p.isReady || false,
          avatarUrl: p.Avatar || p.avatar || p.avatarUrl || '1'
        }))
        console.log('[调试] 刷新后的玩家列表:', roomInfo.players)
      } else {
        console.warn('[调试] 自动加入房间失败:', joinResp.message)
        showNotification(joinResp.message || '加入房间失败', 'error')
      }
    }
  } catch (e) {
    console.warn('[调试] 自动加入房间异常:', e)
  }
  
  // 建立房间SignalR连接并加入组，用于接收 GameStarted 广播（尽早加入，避免错过广播）
  try { 
    console.log('[调试] 开始加入房间SignalR组')
    await joinRoomSignalGroup(route.params.id)
    console.log('[调试] 加入房间SignalR组完成')
  } catch (e) { 
    console.warn('[调试] 加入房间SignalR组失败', e) 
  }
  
  // Fallback：立即查询房间是否已经在游戏中；如果是则直接跳转
  try {
    console.log('[调试] 开始即时房间状态检查')
    const info = await roomAPI.getRoomInfo(roomInfo.id)
    console.log('[调试] 即时房间状态:', info)
    const rd = info.data || {}
    const status = (rd.Status || rd.status || '').toString().toLowerCase()
    const gameId = rd.GameId || rd.gameId || rd.CurrentGameId || rd.currentGameId
    console.log('[调试] 房间状态:', status, '游戏ID:', gameId)
    
    if ((status === 'playing' || status === 'inprogress') && gameId && router.currentRoute.value.name !== 'LineDrawingGame') {
      console.log('[调试] 房间已在游戏中，执行立即跳转')
      addSystemMessage('房间已在游戏中，正在跳转...')
      router.push({ 
        name: 'LineDrawingGame', 
        params: { gameId },
        query: { 
          playerId: userStore.userInfo?.id,
          playerName: userStore.userInfo?.username 
        }
      })
      return
    }
  } catch (e) {
    console.debug('[调试] 即时房间状态检查失败（可忽略）:', e)
  }
  
  console.log('[调试] 开始加载聊天历史')
  await loadChatHistory()
  console.log('[调试] RoomPage onMounted 完成')
})

onBeforeUnmount(async () => {
  // 断开SignalR连接
  try { if (roomSignal.conn) { await roomSignal.conn.stop(); roomSignal.conn = null; roomSignal.joinedRoomId = null } } catch {}
})

// 路由守卫：离开时退出房间
onBeforeRouteLeave(async (to, from, next) => {
  // 允许跳转到任何游戏相关页面（包括新的画线圈地页）而不自动离开房间
  if (to.path.startsWith('/game/') || to.name === 'LineDrawingGame' || to.path.startsWith('/line-drawing-game/')) {
    return next()
  }
  try {
    await roomAPI.leaveRoom(roomInfo.id)
  } catch (error) {
    console.error('自动离开房间失败:', error)
  }
  next()
})
</script>

<style scoped>
.room-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow-x: hidden;
}

.room-page::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 20% 50%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 40% 80%, rgba(79, 172, 254, 0.2) 0%, transparent 50%);
  pointer-events: none;
}

.navbar {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(15px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding: 1rem 0;
  position: relative;
  z-index: 100;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 2rem;
}

.nav-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 1rem;
}

.room-info-nav h1 {
  color: #fff;
  font-size: 1.8rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.room-id-wrapper {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.room-id {
  color: rgba(255, 255, 255, 0.8);
  font-size: 1rem;
  font-weight: 500;
  background: rgba(255, 255, 255, 0.1);
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  backdrop-filter: blur(10px);
}

.copy-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  padding: 0.25rem 0.5rem;
  color: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9rem;
}

.copy-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
}

.nav-actions {
  display: flex;
  gap: 1rem;
  align-items: center;
  flex-wrap: wrap;
}

.main-content {
  padding: 2rem 0;
  position: relative;
  z-index: 10;
}

.room-layout {
  display: grid;
  grid-template-columns: 420px 1fr;
  gap: 2.5rem;
  min-height: 75vh;
  align-items: start;
  max-width: 1600px;
  margin: 0 auto;
}

.sidebar {
  display: flex;
  flex-direction: column;
  gap: 2rem;
  position: sticky;
  top: 2rem;
}

.card {
  background: rgba(255, 255, 255, 0.08);
  backdrop-filter: blur(25px);
  border-radius: 24px;
  border: 1px solid rgba(255, 255, 255, 0.15);
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.1),
    0 4px 16px rgba(0, 0, 0, 0.05),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
  transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  position: relative;
  overflow: hidden;
}

.card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  opacity: 0.6;
}

.card:hover {
  transform: translateY(-4px) scale(1.02);
  box-shadow: 
    0 20px 50px rgba(0, 0, 0, 0.15),
    0 10px 30px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.25);
  background: rgba(255, 255, 255, 0.12);
}

.players-section,
.game-controls {
  padding: 2rem;
}

.game-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.game-buttons .btn {
  width: 100%;
}

.players-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.players-header h3 {
  color: #fff;
  margin: 0;
  font-size: 1.4rem;
  font-weight: 800;
  display: flex;
  align-items: center;
  gap: 0.75rem;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  position: relative;
}

.players-header h3::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 60px;
  height: 3px;
  background: linear-gradient(90deg, #4facfe, #00f2fe);
  border-radius: 2px;
  box-shadow: 0 2px 8px rgba(79, 172, 254, 0.4);
}

.players-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1.5rem;
  max-height: 450px;
  overflow-y: auto;
  padding-right: 12px;
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
}

.player-item {
  display: flex;
  align-items: center;
  gap: 1.25rem;
  padding: 1.5rem;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 18px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  position: relative;
  overflow: hidden;
  backdrop-filter: blur(15px);
  box-shadow: 
    0 4px 20px rgba(0, 0, 0, 0.08),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.player-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.player-item:hover::before {
  opacity: 1;
}

.player-item:hover {
  transform: translateY(-2px);
  background: rgba(255, 255, 255, 0.12);
  border-color: rgba(255, 255, 255, 0.2);
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.12),
    0 4px 16px rgba(102, 126, 234, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.15);
}

.player-item.is-owner {
  border: 2px solid #ffd700;
  background: linear-gradient(135deg, rgba(255, 215, 0, 0.2) 0%, rgba(255, 215, 0, 0.08) 100%);
  box-shadow: 
    0 8px 32px rgba(255, 215, 0, 0.15),
    inset 0 1px 0 rgba(255, 215, 0, 0.2);
}

.player-item.is-ready {
  border: 2px solid #4facfe;
  background: linear-gradient(135deg, rgba(79, 172, 254, 0.2) 0%, rgba(79, 172, 254, 0.08) 100%);
}

.player-item.is-current-user {
  border: 2px solid #667eea;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.2) 0%, rgba(102, 126, 234, 0.08) 100%);
}

.player-item.empty-slot {
  opacity: 0.7;
  border: 2px dashed rgba(255, 255, 255, 0.25);
  background: rgba(255, 255, 255, 0.02);
  cursor: default;
  animation: pulse-empty 3s ease-in-out infinite;
}

@keyframes pulse-empty {
  0%, 100% { opacity: 0.7; }
  50% { opacity: 0.5; }
}

.player-avatar {
  width: 52px;
  height: 52px;
  border-radius: 50%;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.25) 0%, rgba(255, 255, 255, 0.1) 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  flex-shrink: 0;
  border: 2px solid rgba(255, 255, 255, 0.2);
  box-shadow: 
    0 6px 16px rgba(0, 0, 0, 0.1),
    inset 0 1px 2px rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
}

.player-avatar .avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.player-avatar.empty {
  background: rgba(255, 255, 255, 0.05);
  color: rgba(255, 255, 255, 0.4);
  border-style: dashed;
  border-color: rgba(255, 255, 255, 0.2);
  font-size: 1.2rem;
}

.player-info {
  flex: 1;
  min-width: 0;
}

.player-name {
  color: #fff;
  font-weight: 700;
  font-size: 1.1rem;
  margin-bottom: 0.5rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.owner-badge {
  font-size: 1rem;
  filter: drop-shadow(0 2px 4px rgba(255, 215, 0, 0.5));
  animation: crown-glow 2s ease-in-out infinite alternate;
}

@keyframes crown-glow {
  from { filter: drop-shadow(0 2px 4px rgba(255, 215, 0, 0.5)); }
  to { filter: drop-shadow(0 2px 8px rgba(255, 215, 0, 0.8)); }
}

.player-status {
  font-size: 0.9rem;
  font-weight: 600;
}

.status-ready {
  color: #4facfe;
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.status-waiting {
  color: rgba(255, 255, 255, 0.6);
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.player-actions {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  padding: 0.75rem 1.5rem;
  font-size: 0.95rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  border: 1px solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn-primary {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.btn-primary:hover {
  box-shadow: 0 8px 25px rgba(79, 172, 254, 0.4);
}

.btn-secondary {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.05) 100%);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.btn-secondary:hover {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.1) 100%);
  box-shadow: 0 8px 25px rgba(255, 255, 255, 0.2);
}

.btn-success {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
}

.btn-success:hover {
  box-shadow: 0 8px 25px rgba(17, 153, 142, 0.4);
}

.btn-danger {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
}

.btn-danger:hover {
  box-shadow: 0 8px 25px rgba(255, 107, 107, 0.4);
}

.btn-sm {
  padding: 0.5rem 1rem;
  font-size: 0.85rem;
}

.btn-large {
  width: 100%;
  padding: 1.25rem;
  font-size: 1.2rem;
  font-weight: 700;
  border-radius: 16px;
}

.game-controls {
  margin-top: auto;
}

.waiting-message {
  text-align: center;
  color: rgba(255, 255, 255, 0.8);
  font-size: 1rem;
  padding: 1.25rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.chat-section {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-container {
  height: 650px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border-radius: 24px;
  background: rgba(255, 255, 255, 0.06);
  backdrop-filter: blur(25px);
  border: 1px solid rgba(255, 255, 255, 0.12);
  box-shadow: 
    0 12px 40px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2rem 2rem 1.5rem 2rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0.02) 100%);
  border-radius: 24px 24px 0 0;
}

.chat-header h3 {
  color: #fff;
  margin: 0;
  font-size: 1.5rem;
  font-weight: 800;
  display: flex;
  align-items: center;
  gap: 0.75rem;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.loading-chat {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.7);
  gap: 1rem;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #4facfe;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.chat-messages::-webkit-scrollbar {
  display: none;
}

.message {
  display: flex;
  flex-direction: column;
}

.message.is-own-message {
  align-items: flex-end;
}

.system-message {
  text-align: center;
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.9rem;
  padding: 0.75rem 1rem;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  margin: 0.5rem 0;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.system-icon {
  font-size: 1.1rem;
}

.user-message {
  display: flex;
  gap: 1rem;
  max-width: 85%;
  align-items: flex-start;
}

.is-own-message .user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.1) 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.1rem;
  flex-shrink: 0;
  border: 2px solid rgba(255, 255, 255, 0.2);
  margin-top: 0.25rem;
  overflow: hidden;
}

.message-avatar .avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-header {
  display: flex;
  gap: 0.75rem;
  margin-bottom: 0.5rem;
  font-size: 0.85rem;
  align-items: center;
}

.is-own-message .message-header {
  flex-direction: row-reverse;
}

.message-author {
  color: #4facfe;
  font-weight: 700;
}

.message-time {
  color: rgba(255, 255, 255, 0.5);
  font-weight: 500;
}

.message-text {
  background: rgba(255, 255, 255, 0.1);
  padding: 1.25rem 1.5rem;
  border-radius: 20px;
  color: #fff;
  line-height: 1.6;
  word-wrap: break-word;
  white-space: pre-wrap;
  word-break: break-word;
  max-width: 100%;
  border: 1px solid rgba(255, 255, 255, 0.08);
  backdrop-filter: blur(15px);
  font-size: 0.95rem;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.is-own-message .message-text {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.7) 0%, rgba(118, 75, 162, 0.7) 100%);
  border: 1px solid rgba(102, 126, 234, 0.4);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.2);
}

.selectable-text {
  user-select: text !important;
  -webkit-user-select: text !important;
  -moz-user-select: text !important;
  -ms-user-select: text !important;
}

.chat-input {
  padding: 1.5rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(255, 255, 255, 0.03);
}

.input-group {
  display: flex;
  gap: 0.75rem;
  margin-bottom: 1rem;
}

.form-input {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 0.75rem 1rem;
  color: #fff;
  font-size: 0.95rem;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  user-select: text;
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
}

.form-input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.form-input:focus {
  outline: none;
  border-color: #4facfe;
  box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.2);
  background: rgba(255, 255, 255, 0.15);
}

.input-group .form-input {
  flex: 1;
  margin-bottom: 0;
}

.quick-messages {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
  justify-content: center;
}

.quick-btn {
  padding: 0.5rem 1rem;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 0.85rem;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  font-weight: 500;
}

.quick-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  transform: translateY(-1px);
  border-color: rgba(255, 255, 255, 0.3);
}

.quick-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(3px);
}

.leave-modal {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.95) 0%, rgba(118, 75, 162, 0.95) 100%);
  backdrop-filter: blur(25px);
  border-radius: 20px;
  width: 380px;
  max-width: 90vw;
  overflow: hidden;
  box-shadow: 
    0 20px 60px rgba(0, 0, 0, 0.3),
    0 8px 32px rgba(102, 126, 234, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.2);
  animation: modalSlideIn 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: scale(0.8) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.leave-modal-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1.25rem 1.5rem 0.75rem 1.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.leave-icon-small {
  font-size: 1.2rem;
  color: rgba(255, 255, 255, 0.9);
}

.leave-modal-header h3 {
  color: #fff;
  margin: 0;
  font-size: 1.1rem;
  font-weight: 700;
  flex: 1;
}

.leave-close {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: rgba(255, 255, 255, 0.8);
  font-size: 1.2rem;
  cursor: pointer;
  padding: 0.25rem;
  border-radius: 50%;
  transition: all 0.3s ease;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.leave-close:hover {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  transform: rotate(90deg);
}

.leave-modal-body {
  padding: 1.5rem;
  text-align: center;
}

.leave-warning {
  font-size: 2.5rem;
  margin-bottom: 1rem;
  animation: warning-pulse 2s ease-in-out infinite;
}

@keyframes warning-pulse {
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.05); opacity: 0.9; }
}

.leave-message-compact {
  color: #fff;
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.leave-note-compact {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.9rem;
  margin-bottom: 0;
  font-style: italic;
}

.leave-modal-footer {
  display: flex;
  gap: 0.75rem;
  padding: 0 1.5rem 1.5rem 1.5rem;
  justify-content: center;
}

.btn-compact {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 12px;
  font-size: 0.9rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 80px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.btn-compact:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-compact-secondary {
  background: rgba(255, 255, 255, 0.15);
  color: #fff;
}

.btn-compact-secondary:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.25);
  transform: translateY(-1px);
}

.btn-compact-danger {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  color: #fff;
  border-color: rgba(255, 107, 107, 0.5);
}

.btn-compact-danger:hover:not(:disabled) {
  background: linear-gradient(135deg, #ff5252 0%, #e53e3e 100%);
  transform: translateY(-1px);
}

/* 通知组件样式 */
.notification-overlay {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 2000;
  pointer-events: none;
}

.notification {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem 1.5rem;
  border-radius: 16px;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  min-width: 300px;
  animation: slideInRight 0.3s ease-out, fadeOut 0.3s ease-in 2.7s forwards;
  pointer-events: auto;
}

.notification-success {
  background: linear-gradient(135deg, rgba(17, 153, 142, 0.9) 0%, rgba(56, 239, 125, 0.9) 100%);
}

.notification-warning {
  background: linear-gradient(135deg, rgba(255, 193, 7, 0.9) 0%, rgba(255, 152, 0, 0.9) 100%);
}

.notification-error {
  background: linear-gradient(135deg, rgba(255, 107, 107, 0.9) 0%, rgba(238, 90, 82, 0.9) 100%);
}

.notification-info {
  background: linear-gradient(135deg, rgba(79, 172, 254, 0.9) 0%, rgba(0, 242, 254, 0.9) 100%);
}

.notification-icon {
  font-size: 1.5rem;
  flex-shrink: 0;
}

.notification-message {
  color: #fff;
  font-weight: 600;
  font-size: 1rem;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

@keyframes slideInRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
    transform: translateX(0);
  }
  to {
    opacity: 0;
    transform: translateX(100%);
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .room-layout {
    grid-template-columns: 1fr;
    gap: 2rem;
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 1rem;
  }
  
  .nav-content {
    flex-direction: column;
    gap: 1rem;
  }
  
  .room-id-wrapper {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
  
  .chat-container {
    height: 500px;
  }
  
  .players-section,
  .game-controls {
    padding: 1.5rem;
  }
  
  .card:hover {
    transform: none;
  }
  
  .notification {
    min-width: auto;
    width: 100%;
  }
  
  .notification-overlay {
    left: 10px;
    right: 10px;
  }
}
</style>
